<template>
    <view class="content">
        <van-nav-bar :title="scrolling? navBarTitle : '发布真实的评价' " left-arrow @click-left="onClickLeft"
            id="navBar"></van-nav-bar>
        <scroll-view class="scroll-content" scroll-y :lower-threshold="80" @scroll="scrollPage" show-scrollbar="false">
            <view class="pageTop">
                <view class="title"> 发布追评 </view>
                <!-- <view class="subtitle">{{subtitle}}</view> -->
            </view>
            <form @submit="formSubmit" catchreset="formReset">
                <view class="pageMiddle">
                    <view >
                        <view class="goodsDetail">
                            <view class="goodsPic"> <img :src="productInfo.imgUrl" mode="widthFix" alt=""> </view>
                            <view class="goodsText">
                                <!-- <view class="goodsTop"> 发表您对产品的评价</view>
                                <view class="goodsSpecs"> 购买商品规格</view> -->
                                <view class="goodsTop">
                                    <view class="goods_T">{{ productInfo.productName }}</view>
                                    <view class="goods_price">X {{ productInfo.buyNum }}</view>
                                </view>
                                <view class="googsMiddle">
                                    <view class="goods_specs">{{ productInfo.specName }}</view>
                                </view>
                                <view class="goodsBottom">
                                    <view class="money"  v-if="productInfo.productPrice && productInfo.productPrice !==0">￥{{ productInfo.productPrice }}</view>
                                    <view class="jifen_box" v-if="productInfo.maxUsefulPoints && productInfo.maxUsefulPoints!=='0'">
                                        <view class="money">最多可用</view>
                                        <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                            alt=""
                                            style="height: 22rpx; width: 22rpx; margin-right: 6px;margin-left: 6px;" />
                                        {{ productInfo.maxUsefulPoints }}
                                    </view>
                                </view>
                            </view>
                        </view>
                        <view class="overallEvaluation">
                            <view class="text r20 " style="color: #111111;font-size: 28rpx; line-height: 28rpx;"> 商品评价
                            </view>
                            <!-- <view class="icon">
                            <img :src="isSelectedBad ? actBadIcon : inactBadIcon" alt="" @tap="select(0)" style="width: 12px; height: 12px;">
                            <img :src="isSelectedMid ? actMiddleIcon : inactMiddleIcon" alt="" @tap="select(1)" style="width: 12px; height: 12px;">
                            <img :src="isSelectedBest ? actBestIcon : inactBestIcon" alt="" @tap="select(2)" style="width: 12px; height: 12px;">
                            </view> -->
                            <view class="icon">
                                <van-rate :value="valueStar" size="20" color="#FF6203" void-icon="star"
                                    void-color="#eee" @change="onChangeRate" />
                            </view>
                        </view>
                        <view class="judgeTips">
                            <view>
                                <textarea placeholder="发布您的评价，对我们非常重要哦~" :value="productInfo.content"
                                    placeholder-style="font-size: 12px;color: #888888;" :disable-default-padding="true"
                                    @input="handleInput" auto-focus="true" confirm-type="done" maxlength="200"
                                    autoHeight
                                    custom-style="font-size: 12px;line-height:1.5; color:#111111;"></textarea>
                            </view>
                        </view>
                        <view class="uploadPic">
                            <!-- <van-uploader :file-list="fileList" :deletable="true" max-count="4"
                                @after-read="afterRead" @delete="deletedFile" @before-read="beforeRead"
                                accept="media" preview-image multiple :show-upload="true"
                                :capture="['album', 'camera']" upload-text="点击上传图片（最多四张）" :max-duration="60">
                            </van-uploader> -->
                            <view class="preview-list">
                                <view v-for="(file, fIndex) in  productInfo.fileList" :key="fIndex" class="preview-item">
                                    <image :src="file.url" class="preview-image" @click="previewImage(file.url)">
                                    </image>
                                    <view class="delete-icon" @click="deleteImage(fIndex)">×</view>
                                </view>
                            </view>
                            <!-- 上传按钮 -->
                            <view class="upload-btn" @click="chooseImage">
                                <image class="upload-icon"
                                    src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/uploaderPic.png"
                                    mode="aspectFit"></image>
                                <text class="upload-text">点击上传图片（最多九张）</text>
                            </view>
                        </view>
                    </view>

                    <view class="niming">
                        <van-checkbox :value="isAnonymous" @change="onChange" checked-color="#FF6203">匿名评价</van-checkbox>
                    </view>
                </view>

            </form>
            <view class="btn-area">
                <button plain type="waring" @tap="submitFollowComment" class="button">确认评价</button>
            </view>
            <!-- <view class="btn-area custom-button">
                <van-button type="primary" @click="submitApply" form-type="submit" class="">确认评价</van-button>
            </view> -->
        </scroll-view>
    </view>
</template>
<script>
import {submitFollowupsApi} from '@/api/judge'

export default {

    components: {
    },
    data () {
        return {
            navBarTitle: '发布真实的评价',
            scrolling: false,
            subtitle:'商品评价',
            fileList: [],
            fileUrl: "",
            show: false,
            sysFileId: null,
            isAnonymous:true, //是否匿名评价
            content:'哈哈红红火火恍恍惚惚哈哈哈哈哈哈哈哈哈哈哈红红火火恍恍惚惚哈哈哈哈哈哈哈哈哈hhhhh哈哈红红火火恍恍惚惚哈哈哈哈哈哈哈哈哈', // 输入框内容  评论内容
            inactBadIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/bad.png',
            actBadIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/bad_act.png',
            inactMiddleIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/middle.png',
            actMiddleIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/middle_act.png',
            inactBestIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/best.png',
            actBestIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/best_act.png',
            isSelectedBad:false,
            isSelectedMid:false,
            isSelectedBest:false,
            valueStar:5,
            productInfo:{
                content: '', // 追评内容
                fileList: [] // 追评图片
            },
            // goodsList:[
            // {
            //         Id: 11,
            //         imgurl: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/judge01.png',
            //         title: '黄芪杞姜枣糕红枣',
            //         price: '15',
            //         num: '1',
            //         score: 190,
            //         money: '120',
            //         specs: '口味一：五斤装',
            //         isShouQing: false,
            //         isXiajia: false
            //     },
            //     {
            //         Id: 12,
            //         imgurl: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/judge01.png',
            //         title: '黄芪杞姜枣糕红枣枸杞 口味一：五斤装',
            //         price: '16',
            //         num: '1',
            //         score: 190,
            //         money: '120',
            //         specs: '口味一：五斤装',
            //         isShouQing: false,
            //         isXiajia: false
            //     },
            // ],
            fileList: [], // 图片列表
            commentId:undefined,
            params:null,

        }

    },

    computed: {},

    watch: {},
    onLoad (data ) {
        if(data && data.params){
            this.params = JSON.parse(decodeURIComponent(data.params))
            console.log(this.params,'params')
            this.productInfo = {
                content: '',        // 初始化评价内容
                fileList: [],       // 初始化图片列表
                ...this.params.productInfo  // 保留传入参数
            }
        }
    },
    onReady () {
    },

    methods: {
        // 滑动
        scrollPage (e) {
            console.log(e.detail.scrollTop, this.scrolling)
            if (e.detail.scrollTop > 25 && !this.scrolling) {
                this.scrolling = true
            } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
                this.scrolling = false
            }
        },
        // 返回键
        onClickLeft () {
            uni.navigateBack()
        },



        handleInput(e) {
            console.log('输入框输入的内容是：', e.detail.value);
            const value=e.detail.value
            if (value.length > 200) {
                wx.showToast({
                    title: '超出字数限制',
                    icon: 'none'
                });
                return;
            }
            this.message= e.detail.value
        },

        onChange(e){
            console.log(e.detail)
            this.isAnonymous = !this.isAnonymous
        },


        select(val){
            if(val===0){
                this.isSelectedBad=!this.isSelectedBad
                this.isSelectedMid=false
                this.isSelectedBest=false
            }else if(val===1){
                this.isSelectedBad=false
                this.isSelectedMid=! this.isSelectedMid
                this.isSelectedBest=false
            }else{
                this.isSelectedBad=false
                this.isSelectedMid=false
                this.isSelectedBest=!this.isSelectedBest
            }
        },
        // 星级评分
        onChangeRate(e){
            console.log(e,'pingfen ')
            this.valueStar=e.detail
        },
        async uploadToOSS(file) {
            const OSS_CONFIG = {
                region: 'oss-cn-beijing',
                accessKeyId: 'LTAI5t977yzTgy3KuHsZpNGp',
                accessKeySecret: '3XClQa1PDAqqHyK1avhz5npkhN7Uel',
                bucket: '17lelife-bucket',
                host: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/',
                dir: 'WeChat-App-Picture/comment/service/'
            };

            try {
                // 强化文件路径校验
                const fileRealPath = file.tempFilePath || file.path || file.url;
                if (!fileRealPath) {
                    throw new Error('无法获取有效文件路径，请重新选择文件');
                }

                // 安全获取文件扩展名
                const getExtension = () => {
                    return file.type?.split('/')[1] ||
                        file.name?.split('.').pop() ||
                        fileRealPath.split('.').pop() ||
                        'jpg';
                };

                // 生成唯一文件名
                const fileName = `${Date.now()}_${Math.random()
                    .toString(36)
                    .substr(2, 12)}.${getExtension().toLowerCase()}`;
                const filePath = `${OSS_CONFIG.dir}${fileName}`;

                // 生成安全策略
                const generatePolicy = () => {
                    const policy = {
                        expiration: new Date(Date.now() + 3600000).toISOString(),
                        conditions: [
                            ["content-length-range", 0, 10485760], // 10MB限制
                            ["starts-with", "$key", OSS_CONFIG.dir]
                        ]
                    };
                    return CryptoJS.enc.Base64.stringify(
                        CryptoJS.enc.Utf8.parse(JSON.stringify(policy))
                    );
                };

                // 生成签名
                const policy = generatePolicy();
                const signature = CryptoJS.HmacSHA1(policy, OSS_CONFIG.accessKeySecret)
                    .toString(CryptoJS.enc.Base64);

                // 执行上传
                const uploadResult = await new Promise((resolve, reject) => {
                    uni.uploadFile({
                        url: OSS_CONFIG.host,
                        filePath: fileRealPath,
                        name: 'file',
                        formData: {
                            key: filePath,
                            policy: policy,
                            OSSAccessKeyId: OSS_CONFIG.accessKeyId,
                            signature: signature,
                            success_action_status: '200'
                        },
                        success: (res) => {
                            if (res.statusCode === 200) {
                                resolve(`${OSS_CONFIG.host}${filePath}`);
                            } else {
                                reject(new Error(`上传失败，状态码：${res.statusCode}`));
                            }
                        },
                        fail: (err) => {
                            reject(new Error(`上传请求失败：${err.errMsg}`));
                        }
                    });
                });

                return uploadResult;
            } catch (error) {
                console.error('OSS上传失败详情:', {
                    error,
                    fileObject: file,
                    pathAttempts: {
                        tempFilePath: file.tempFilePath,
                        path: file.path,
                        url: file.url
                    }
                });
                throw new Error(`文件上传失败：${error.message}`);
            }
        },
       // 上传图片
    //    async chooseImage() {
    //         const goods = this.goodsList.find(g => g.Id === this.currentGoodsId);
    //         if (!goods) return;
    //         try {
    //             const res = await uni.chooseImage({
    //                 count: 9 - goods.comment.files.length, // 最多可以选择的图片数量
    //                 sizeType: ['compressed'],
    //                 sourceType: ['album', 'camera'],
    //                 success: (res) => {
    //                     console.log('选择图片成功:', res.tempFiles);
    //                     console.log('选择图片成功，临时路径:', res.tempFilePaths);
    //                     // uni.showLoading({ title: '上传中...' });
    //                     // 直接使用临时路径，不上传OSS
    //                     const newFiles = res.tempFilePaths.map(url => ({
    //                         url,
    //                         status: 'done',
    //                         isImage: true
    //                     }));
    //                     const mergedFiles = [...this.fileList, ...newFiles];
    //                     const uniqueFiles = mergedFiles.filter(
    //                         (file, index, self) =>
    //                             self.findIndex(f => f.url === file.url) === index
    //                     );

    //                     this.fileList = uniqueFiles.slice(0, 9);

    //                     this.fileList = uniqueFiles.slice(0, 9); // 确保最多9张图片
    //                     console.log('更新后文件列表:', JSON.stringify(this.fileList))


    //                     // res.tempFiles.forEach(async (file) => {
    //                     //     try {

    //                     //         // 阿里云OSS上传
    //                     //         // const ossUrl = await this.uploadToOSS(file);
    //                     //         // this.fileList = [...this.fileList, {
    //                     //         //     url: ossUrl,
    //                     //         //     status: 'done',
    //                     //         //     isImage: true
    //                     //         // }];
    //                     //         // console.log('上传完成，更新后文件列表:', JSON.stringify(this.fileList))
    //                     //     } catch (error) {
    //                     //         console.error('上传失败:', error);
    //                     //         uni.showToast({
    //                     //             title: error.errMsg || '选择图片失败',
    //                     //             icon: 'none'
    //                     //         });
    //                     //     } finally {
    //                     //         uni.hideLoading();
    //                     //     }
    //                     // });
    //                 }
    //             });
    //         } catch (error) {
    //             uni.showToast({
    //                 title: error.errMsg || '选择图片失败',
    //                 icon: 'none'
    //             });
    //             uni.hideLoading();
    //         }
    //     },
        async chooseImage() {
            try {
                uni.showLoading({ title: '上传中...' });
                const res = await uni.chooseImage({
                    count: 9 - this.productInfo.fileList.length,
                    sizeType: ['compressed'],
                    sourceType: ['album', 'camera']
                });

                // 强化去重逻辑
                const uniqueFiles = res.tempFilePaths.filter(path => {
                    return !this.productInfo.fileList.some(f =>
                        f.url === path || f.url.includes(path.split('/').pop())
                    );
                });

                const uploadPromises = uniqueFiles.map(async (filePath) => {
                    const ossUrl = await this.uploadToOSS({
                        tempFilePath: filePath,
                        path: filePath,
                        type: res.tempFiles[0].type
                    });
                    return {
                        url: ossUrl,
                        status: 'done',
                        isImage: true,
                        localPath: filePath
                    };
                });

                const newFiles = await Promise.all(uploadPromises);
                this.productInfo.fileList = [...this.productInfo.fileList, ...newFiles].slice(0, 9);

            } catch (error) {
                uni.showToast({ title: error.message || '上传失败', icon: 'none' });
            } finally {
                uni.hideLoading();
            }
        },

        deleteImage(index) {
            this.productInfo.fileList.splice(index, 1);
        },
        previewImage(url) {
            // 生成有效的 URL 列表
            const validUrls = this.productInfo.fileList
                .map(file => file.url)
                .filter(url => typeof url === 'string' && url.length > 0);

            if (validUrls.length === 0) {
                uni.showToast({ title: '暂无可预览图片', icon: 'none' });
                return;
            }

            // 检查当前 URL 是否有效
            const current = validUrls.includes(url) ? url : validUrls[0];
            
            uni.previewImage({
                current,
                urls: validUrls,
                fail: (err) => {
                    console.error('预览失败:', err);
                    uni.showToast({
                        title: '图片加载失败，请稍后重试',
                        icon: 'none'
                    });
                }
            });
        },

        // 确认按钮
        async submitFollowComment(event) {//点击提交按钮上传设置banner图数据
            try {
                if (!this.productInfo.content || this.productInfo.content.length < 10) {
                    return uni.showToast({
                        title: '评价内容不能少于10个字',
                        icon: 'none'
                    });
                }

                const params = {
                    commentId: this.commentId,
                    content: this.productInfo.content,
                    commentImgUrls: this.productInfo.fileList.map(f => f.url),
                    // goodsId: this.productInfo.productId, // 添加商品ID
                    rating: this.valueStar,
                    isAnonymous: this.isAnonymous ? 1 : 0,
                };

                const res = await submitFollowupsApi(params);
                uni.showToast({ title: '提交成功' });
                setTimeout(() => uni.navigateBack(), 1500);

            } catch (error) {
                uni.showToast({
                    title: error.message || '提交失败',
                    icon: 'none'
                });
            }
        },


    }

}
</script>
<style lang="scss" scoped>

.content {
    background-color: #ffffff;
    display: flex;
    flex-direction:column;
    overflow:hidden;
    box-sizing: border-box;
    height:100vh;
}
.scroll-content {
    flex: 1;
    height: 1px;
}

.pageTop{
    margin: 0px 24px;
    padding-top: 17px;

    .title{
        font-size: 60rpx;
        color: #111111;
        text-align: left;
        line-height: 60rpx;
    }

    .subtitle{
        padding-top: 24px;
        text-align: left;
        font-size: 28rpx;
        line-height: 28rpx;
        color: #111111;
        
    }



}


.pageMiddle{
    padding-left: 24px;
    padding-right: 24px;
    padding-bottom: 160rpx;
}
.goodsDetail{
    margin-top: 24px;
    // padding: 24px;
    padding: 12px;
    border-radius:4px;
    background: #f9f9f9;
    // width: calc(100% - 48px );
    display: flex;
    // align-items: center;

    .goodsPic{
        width: 20%;
        border-radius: 4px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        img{
            width: 100%;
            height: auto;
            border-radius: 4px;
        }
    }
    .goodsText{
        // position: relative;
        // width: 80%; 
        padding-left: 24rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        // text-align: left;
        width:calc(80% - 24rpx);
    }

    .goodsTop {
        // position: absolute;
        // top: 2%;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .goods_T {
          font-size: 28rpx;
          text-align: left;
          color: #111111;
          max-width: 80%;
          line-height: 28rpx;
          // margin-top: 9px;  //display：flex   中 元素居中
          white-space: nowrap;
          /* 防止文本换行 */
          overflow: hidden;
          /* 超出部分隐藏 */
          text-overflow: ellipsis;
          /* 显示省略号 */

        }

        // 商品价格
        .goods_price {
          font-size: 28rpx;
          color: #111111;
          line-height:28rpx;
        }
      }

      .googsMiddle {
        // position: absolute;
        // top: 25%;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 24rpx;
        color: #666666;

        .goods_specs {
          // margin-top: 7px;
          max-width: 80%;
          font-size: 24rpx;
          text-align: left;
          color: #666666;
          //   line-height: 11px;

          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: normal;
        }

        // .goods_num {
        //   font-size: 22rpx;
        //   line-height: 22rpx;
        //   color: #666666;
        // }

      }
    .goodsBottom{
      display: flex;
      align-items: center;
      width:100%;

    .money{
      font-size: 28rpx;
      text-align: left;
      color: #111111;
      line-height: 28rpx;
    }
    .jifen_box{
        display: flex;
        align-items: center;
        // color: #111111;
        margin-left: 6px;
        font-weight: bolder;
        font-size: 28rpx;
        text-align: left;
        color: #111111;
        line-height: 28rpx;
        height: 28rpx;
    }
  }
}
.judgeTips{
    padding: 48rpx 0rpx 14rpx 0rpx;
    font-size: 24rpx;
    text-align: left;
    color: #888888;
    border-bottom: 1px solid #f9f9f9;
}
.uploadPic{
    margin-top:36rpx;
 
}
.uploader{
    background-color: #f9f9f9;
    padding: 24px 12px;
    border-radius: 25px;
    border:1px dashed #f9f9f9;
}
.text{
    font-size: 24rpx;
    color: #888888;
    line-height: 24rpx;
}

.overallEvaluation{
    margin-top: 24px;
    display: flex;
    align-items: center;
}
.icon{
    display: flex;
}
.icon img{
    margin-right: 25px;
}

.niming{
    display: flex;
    margin-top: 12px;
}
.radioBox{
    display: flex;
    align-items: center;
}
// 上传图片
.custom-uploader {
    padding: 15px;
}

.upload-btn {
    width: 174rpx;
    height: 174rpx;
    border: 1px dashed #ddd;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
    background-color: #f0f0f0;
}

.upload-icon {
    width: 40rpx;
    height: 34rpx;
}

.upload-text {
    font-size: 24rpx;
    color: #888888;
    margin-top: 8px;
    text-align: center;
}

.preview-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.preview-item {
    position: relative;
    width: 174rpx;
    height:174rpx;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 20rpx;
}

.preview-image {
    width: 100%;
    height: 100%;
}

.delete-icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 24px;
    height: 24px;
    background: rgba(0,0,0,0.5);
    color: white;
    text-align: center;
    line-height: 24px;
    border-radius: 0 0 0 8px;
}
::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep #navBar .van-icon {
    color: #242629 !important;
}

::v-deep .van-icon-arrow{
    color:#FF6203 !important ;
}

:v-deep .van-uploader{
    border-radius: 4px !important;
}

.r20{
    margin-right: 20px;
}
.l6{
    margin-left: 6px;
}
.btn-area{
    position: fixed;
    bottom: 0;
    width: calc(100% - 48px);
    padding-left: 24px !important;
    padding-right: 24px !important;
    display: flex;
    background: #ffffff;
    z-index: 100;
    height: 72px;
}


button{
    background-color: #FF6203;
    width: 100%;
    border-radius: 38px;
    font-size:28rpx;
    text-align: center;
    color: #FFFFFF;
    height: 76rpx;
    line-height: 76rpx;
    /* padding-top: 13px;
    padding-bottom: 13px; */
}
button[plain]{
    border: none;
}
textarea{
    min-height: 12px !important;
    line-height: 1.5 !important;
    color:#111111 !important;
}
::v-deep .van-uploader__upload-text {
    text-align: center !important;
}

</style>
